package com.sphere.freereader.impl;

import android.widget.ImageView;

import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageLoader;

/**
 * Created by aquarius on 2016/9/4.
 */
public class ReaderImageListener implements ImageLoader.ImageListener {

    private ImageView view;
    private int defaultImageResId;
    private int errorImageResId;

    private ReaderImageListener() {

    }

    private ReaderImageListener(ImageView view, int defaultImageResId, int errorImageResId) {
        this.view = view;
        this.defaultImageResId = defaultImageResId;
        this.errorImageResId = errorImageResId;
    }

    public static ReaderImageListener getInstance(ImageView view, int defaultImageResId, int errorImageResId) {
        return new ReaderImageListener(view, defaultImageResId, errorImageResId);
    }


    @Override
    public void onResponse(ImageLoader.ImageContainer response, boolean isImmediate) {
        if (response.getBitmap() != null) {
            if (view.getTag() == null || (view.getTag() != null && view.getTag().equals(response.getRequestUrl()))) {
                view.setImageBitmap(response.getBitmap());
            }
        } else if (defaultImageResId != 0) {
            if (view.getTag() == null || (view.getTag() != null && view.getTag().equals(response.getRequestUrl()))) {
                view.setImageResource(defaultImageResId);
            }
        }
    }

    @Override
    public void onErrorResponse(VolleyError error) {

    }
}
